using System;
using System.Threading;
using Microsoft.SPOT.Hardware;

using SecretLabs.NETMF.Hardware.NetduinoPlus;

namespace Coding4Fun.Maelstrom.Hardware.Modules
{
	public static class Music
	{
		public static int DamageTrack = 1;

		// 00 - Music STOP (pin to 14 on Music Board)
		// 01 - Music 01
		// 02 - Music 02
		// 03 - Music 03
		// 04 - Music 04
		// 05 - PWM RED
		// 06 - PWM GREEN
		// 07 - Music 05
		// 08 - Music 06
		// 09 - PWM BLUE
		// 10 - PWM RESERVED
		// 11 - SPI (addressable lighting)
		// 12 - Music 07
		// 13 - SPI (addressable lighting)

		private static readonly OutputPort StopMusic = new OutputPort(Pins.GPIO_PIN_D0, true);

		private static readonly OutputPort Track1 = new OutputPort(Pins.GPIO_PIN_D1, true);
		private static readonly OutputPort Track2 = new OutputPort(Pins.GPIO_PIN_D2, true);
		private static readonly OutputPort Track3 = new OutputPort(Pins.GPIO_PIN_D3, true);
		private static readonly OutputPort Track4 = new OutputPort(Pins.GPIO_PIN_D4, true);
		private static readonly OutputPort Track5 = new OutputPort(Pins.GPIO_PIN_D7, true);
		private static readonly OutputPort Track6 = new OutputPort(Pins.GPIO_PIN_D8, true);
		private static readonly OutputPort Track7 = new OutputPort(Pins.GPIO_PIN_D12, true);

		private const int MaxTrack = 7;
		private static readonly Random RandomNumber = new Random();

		public static void PlayRandom()
		{
			// gives you 0 to less than max, with max of 6 put it, we get 0 to 5, we want 1 to 6
			// adding one fixes this offset
			var trackNum = RandomNumber.Next(MaxTrack) + 1; 

			PlayTrack(trackNum);
		}

		public static void PlayTrack(int track)
		{
			switch (track)
			{
				case 1:
					TogglePin(Track1);
					break;
				case 2:
					TogglePin(Track2);
					break;
				case 3:
					TogglePin(Track3);
					break;
				case 4:
					TogglePin(Track4);
					break;
				case 5:
					TogglePin(Track5);
					break;
				case 6:
					TogglePin(Track6);
					break;
				case 7:
					TogglePin(Track7);
					break;
				default:
					// stop all, invalid choice
					TogglePin(StopMusic);
					break;
			}
		}

		public static void Stop()
		{
			TogglePin(StopMusic);
		}

		private static void TogglePin(OutputPort port)
		{
			var t = new Thread(() =>
				                   {
					                   port.Write(false);
					                   Thread.Sleep(50);
					                   port.Write(true);
				                   });

			t.Start();
		}
	}
}